<template>
  <div>图片去除白边</div>
  <div>
    <el-row type="flex">
      <el-upload :before-upload="onUpload1" :multiple="true">
        <el-button>上传图</el-button>
      </el-upload>
      <el-button v-if="src.length > 0" @click="zip" style="margin-left:10px;">批量下载</el-button>
    </el-row>
    <div v-for="(item, index) in src" :key="index">
      <img :src="item.dataURL" alt="" />
      <el-button @click="download(item, index)">下载图片</el-button>
    </div>
  </div>
</template>
<script>
import { markRaw } from 'vue'
import { exportImage } from './dataURLSaveFile.js'
import saveAs from '@/libs/FileSaver.js'
import JSZip from 'jszip'
export default {
  data() {
    return {
      src: []
    }
  },
  methods: {
    onUpload1(file) {
      this.upload(file).then((res) => {
        this.clearWhitePic(res)
      })
      return false
    },
    download(item, index) {
      exportImage(item.dataURL, item.name)
    },
    zip() {
      var zip = new JSZip()
      //zip.file('Hello.txt', 'Hello World\n')
      var img = zip.folder('images')
      this.src.forEach((res, index) => {
        let dataURL = res.dataURL.split(',')[1]
        img.file(res.name, dataURL, { base64: true })
      })
      zip.generateAsync({ type: 'blob' }).then(function(content) {
        // see FileSaver.js
        saveAs(content, 'example.zip')
      })
    },
    /**
     * 清除图片白边.
     *
     * @param {} img
     */
    clearWhitePic(img) {
      let data = img.imgData.data
      let { width, height } = img.imgData
      console.log(width, height)
      let left = 0,
        top = 0,
        right = width - 1,
        bottom = height - 1

      //top
      const findTop = () => {
        for (var y = 0; y < height; y++) {
          for (var x = 0; x < width; x++) {
            let i = (y * width + x) * 4 + 3
            let alpha = data[i]
            //console.log(x, y)
            if (alpha == 0) {
            } else {
              top = y
              return top
            }
          }
        }
      }
      //left
      const findLeft = () => {
        for (var x = 0; x < width; x++) {
          for (var y = 0; y < height; y++) {
            let i = (y * width + x) * 4 + 3
            let alpha = data[i]
            //console.log(x, y)
            if (alpha == 0) {
            } else {
              left = x
              return left
            }
          }
        }
      }

      //right
      const findRight = () => {
        for (var x = width - 1; x > 0; x--) {
          for (var y = 0; y < height; y++) {
            let i = (y * width + x) * 4 + 3
            let alpha = data[i]
            //console.log(x, y)
            if (alpha == 0) {
              //这边其实已经过渡到有内容的地方了，因为开头是空白
              //right = x
            } else {
              right = x
              return right
            }
          }
        }
      }
      //bottom
      const findBottom = () => {
        for (var y = height - 1; y > 0; y--) {
          for (var x = width - 1; x > 0; x--) {
            let i = (y * width + x) * 4 + 3
            let alpha = data[i]
            //console.log(x, y)
            if (alpha == 0) {
              //这边其实已经过渡到有内容的地方了，因为开头是空白
              //bottom = y
            } else {
              bottom = y
              return bottom
            }
          }
        }
      }
      top = findTop()
      left = findLeft()
      right = findRight()
      bottom = findBottom()
      let clipRect = {
        x: left,
        y: top,
        width: right - left + 1,
        height: bottom - top + 1
      }

      this.createClipImg(img.img, clipRect, img)
    },
    createClipImg(source, clipRect, img) {
      var canvas = this.createCanvas(clipRect.width, clipRect.height)
      var ctx = canvas.getContext('2d')
      ctx.drawImage(source, -clipRect.x, -clipRect.y)
      this.src.push({
        dataURL: canvas.toDataURL(),
        name: img.name
      })
    },
    createCanvas(width, height) {
      var canvas = document.createElement('canvas')
      canvas.width = width
      canvas.height = height
      return canvas
    },
    upload(file) {
      return new Promise((resolve) => {
        let fr = new FileReader()
        fr.onload = (e) => {
          var img = new Image()
          img.src = e.target.result
          img.onload = () => {
            var canvas = this.createCanvas(img.width, img.height)
            var ctx = canvas.getContext('2d')
            ctx.drawImage(img, 0, 0)
            let imgData = ctx.getImageData(0, 0, img.width, img.height)
            resolve({
              img,
              imgData,
              src: e.target.result,
              name: file.name
            })
          }
        }
        fr.readAsDataURL(file)
      })
    }
  }
}
</script>
